// -----------------------------------------------
// Author:     code34 nicolas_boiteux@yahoo.fr
// Edited by:  Neumatic
// Warcontext: Create sheeps on road
// -----------------------------------------------

private [
	"_roads",
	"_position",
	"_type",
	"_back",
	"_road",
	"_civiltype",
	"_civil",
	"_group",
	"_active"
];

_position = _this select 0;

_back = [];

_roads = _position nearRoads 400;
{
	if !((count (roadsConnectedTo _x) > 1) and (count (nearestObjects [_x, ["House"], 20]) > 0)) then {
		_roads = _roads - [_x];
	};
} foreach _roads;

if (count _roads == 0) exitWith {};

_active = createTrigger ["EmptyDetector", _position];
_active setTriggerArea [1000, 1000, 0, false];
_active setTriggerActivation ["WEST", "PRESENT", true];
_active setTriggerStatements ["", "", ""];

_group = createGroup civilian;
for "_x" from 1 to (random 4) do {
	_road = _roads call BIS_fnc_selectRandom;

	if (random 1 > 0.1) then {
		_position = ((selectBestPlaces [position _road, 100, "hills", 1, 10] select 0) select 0);
	} else {
		_position = position _road;
	};

	for "_x" from 1 to (random 30) do {
		_type = wcsheeps call BIS_fnc_selectRandom;
		_back = _back + [[_type, _position]];
	};
};

while {true} do {
	// Restore civils
	if (west countSide list _active == 0) then {
		{
			_back = _back + [[typeOf _x, position _x]];
			_x removeAllEventHandlers "Killed";
			_x setDammage 1;
			deleteVehicle _x;
		} foreach (units _group);
		waitUntil {(west countSide list _active > 0)};
		_group = createGroup civilian;
		{
			_civiltype = _x select 0;
			_civil = _group createUnit [_civiltype, (_x select 1), [], 0, "NONE"];
			_civil setSpeedMode "limited";
			_civil setBehaviour "safe";
			_civil allowFleeing (random 0.8);
			_civil stop true;
			_civil setDir (random 360);
			_civil setVariable ["wcprotected", true, false];
			_civil setVariable ["civilrole", "animal", true];
		} foreach _back;
		_back = [];
	};
	sleep 5;
};

diag_log "WARCONTEXT: GENERATE SHEEPS ON ROAD";